package com.aiwei.tdjk.service.impl;

import com.aiwei.tdjk.bean.Pager;
import com.aiwei.tdjk.dao.extend.UserExtendMapper;
import com.aiwei.tdjk.dto.request.GetUserPagerRequest;
import com.aiwei.tdjk.entity.User;
import com.aiwei.tdjk.entity.UserExample;
import com.aiwei.tdjk.entity.UserOrganizationJob;
import com.aiwei.tdjk.enums.UserStatusEnum;
import com.aiwei.tdjk.service.PasswordService;
import com.aiwei.tdjk.service.UserService;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by yanfeng on 2016/12/15.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserExtendMapper userExtendMapper;



    @Autowired
    private PasswordService passwordService;


    @Override
    public User get(long id) {
        return userExtendMapper.selectByPrimaryKey(id);
    }

    /**
     * 暂时只是同步用户信息，没有同步对应的组关系
     *
     * @param user
     */
    @Override
    public void save(User user) {

        user.setSalt(RandomStringUtils.randomAlphanumeric(10));
        user.setPassword(passwordService.encryptPassword(user.getUsername(), user.getPassword(), user.getSalt()));
        userExtendMapper.insertSelective(user);

    }











    /**
     * 使用系统用户对象属性设置到Activiti User对象中
     *
     * @param user         系统用户对象
     * @param activitiUser Activiti User
     */
    private void cloneAndSaveActivitiUser(User user, org.activiti.engine.identity.User activitiUser) {
        activitiUser.setFirstName(user.getUsername());
        activitiUser.setLastName(StringUtils.EMPTY);
        activitiUser.setPassword(StringUtils.EMPTY);
        activitiUser.setEmail(user.getEmail());
//        activitiUser.setEmployeeId(user.getEmployeeId());
//        activitiUser.setFullName(user.getFullName());
    }

    @Override
    public int update(User user) {
        return userExtendMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public int delete(Long id) {

        // 查询需要删除的用户对象
        User user = get(id);
        if (user == null) {
//            throw new Exception("删除用户时，找不到ID为的用户");
            return 0;
        }
        /**
         * 同步删除Activiti User Group
         */
//        List<Role> roleList = user.getRoleList();
//        for (Role role : roleList) {
//            identityService.deleteMembership(userId.toString(), role.getEnName());
//        }
        // 同步删除Activiti User  软删除不需要，万一改回来
//        identityService.deleteUser(id.toString());
//
        // 删除本系统用户
        user.setDeleted(true);
        return userExtendMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public int delete(Long[] ids) {
        if (ids != null && ids.length > 0) {
            for (Long id : ids) {
                delete(id);
            }
        }
        return ids.length;
    }

    /**
     * 获取分页列表
     *
     * @param request
     * @return
     */
    @Override
    public Pager<User> find(GetUserPagerRequest request) {
        request.webParamConvert();
        List<User> userList = userExtendMapper.find(request);
        int totalCount = userExtendMapper.getTotalCount(request);
        Pager<User> pager = new Pager<>();
        pager.setPageNumber(request.getPageNumber());
        pager.setPageSize(request.getPageSize());
        pager.setList(userList);
        pager.setTotalCount(totalCount);
        return pager;
    }

    @Override
    public User findByUsername(String name) {
        if (name == null) {
            return null;
        }else{
            UserExample example = new UserExample();
            example.or().andUsernameEqualTo(name);
            List<User> users = userExtendMapper.selectByExample(example);
            if (users.isEmpty())
                return null;
            return users.get(0);
        }
    }

    @Override
    public User findByUsernameOrMobileOrEmailOrEmployeeId(String name) {
        if (name == null) {
            return null;
        }else{
            UserExample example = new UserExample();
            example.or().andUsernameEqualTo(name);
            example.or().andEmailEqualTo(name);
            example.or().andMobilePhoneNumberEqualTo(name);
            example.or().andEmployeeIdEqualTo(name);
            List<User> users = userExtendMapper.selectByExample(example);
            if (users.isEmpty())
                return null;
            return users.get(0);
        }
    }

    @Override
    public User findByUsername(String name, Long id) {
        if (name == null) {
            return null;
        } else {
            UserExample example = new UserExample();
            if (id == null) {
                example.or().andUsernameEqualTo(name);
            } else {
                example.or().andUsernameEqualTo(name).andIdNotEqualTo(id);
            }
            List<User> users = userExtendMapper.selectByExample(example);
            if (users.isEmpty())
                return null;
            return users.get(0);
        }
    }

    @Override
    public User findByMobilePhoneNumber(String mobilePhoneNumber, Long id) {
        if (mobilePhoneNumber == null) {
            return null;
        } else {
            UserExample example = new UserExample();
            if (id == null) {
                example.or().andMobilePhoneNumberEqualTo(mobilePhoneNumber);
            } else {
                example.or().andMobilePhoneNumberEqualTo(mobilePhoneNumber).andIdNotEqualTo(id);
            }
            List<User> users = userExtendMapper.selectByExample(example);
            if (users.isEmpty())
                return null;
            return users.get(0);
        }
    }

    @Override
    public User findByEmail(String email, Long id) {
        if (email == null) {
            return null;
        } else {
            UserExample example = new UserExample();
            if (id == null) {
                example.or().andEmailEqualTo(email);
            } else {
                example.or().andEmailEqualTo(email).andIdNotEqualTo(id);
            }//为了验证修改重复数据
            List<User> users = userExtendMapper.selectByExample(example);
            if (users.isEmpty())
                return null;
            return users.get(0);
        }
    }

    @Override
    public User findEmployeeId(String employeeId, Long id) {
        if (employeeId == null) {
            return null;
        } else {
            UserExample example = new UserExample();
            if (id == null) {
                example.or().andEmployeeIdEqualTo(employeeId);
            } else {
                example.or().andEmployeeIdEqualTo(employeeId).andIdNotEqualTo(id);
            }//为了验证修改重复数据
            List<User> users = userExtendMapper.selectByExample(example);
            if (users.isEmpty())
                return null;
            return users.get(0);
        }
    }

    @Override
    public UserOrganizationJob findUserOrganization(User user, Long organizationId, Long jobId) {
        return null;
    }

    @Override
    public Pager<UserOrganizationJob> findUserOrganizationJobOnNotExistsOrganizationOrJob() {
        return null;
    }

    @Override
    public void deleteUserOrganizationJobOnNotExistsUser() {

    }

    @Override
    public void changePassword(Long[] ids, String newPassword) {
        for (Long id : ids) {
            User user = get(id);
            user.setSalt(RandomStringUtils.randomAlphanumeric(10));
            user.setPassword(passwordService.encryptPassword(user.getUsername(), newPassword, user.getSalt()));
            update(user);
            //todo log
        }
    }

    @Override
    public Set<Map<String, Object>> findIdAndNames(String terms) {

        UserExample example = new UserExample();
        example.or().andFullNameLike("%" + terms + "%").andDeletedEqualTo(false);
        List<User> users = userExtendMapper.selectByExample(example);

        return Sets.newHashSet(
                Lists.transform(
                        users,
                        new Function<User, Map<String, Object>>() {
                            @Override
                            public Map<String, Object> apply(User input) {
                                Map<String, Object> data = Maps.newHashMap();
                                data.put("label", input.getFullName());
                                data.put("domiciles", "");
                                data.put("value", input.getId());
                                return data;
                            }
                        }
                )
        );


    }

    /**
     * 通过用户所在组织查询组织员工
     *
     * @param userId
     * @return
     */
    @Override
    public List<User> findUserByOrganization(Long userId) {
        return userExtendMapper.findUserByOrganization(userId);
    }

    /**
     * 修改会员的状态
     *
     * @param ids
     * @param newStatus
     * @param reason
     */
    @Override
    public void changeStatus(Long[] ids, UserStatusEnum newStatus, String reason) {
        for (Long id : ids) {
            User user = get(id);
            user.setStatus(newStatus.getCode().byteValue());
            update(user);
        }
    }

    @Override
    public List<User> findUsersByIds(List<Long> userIds) {
        UserExample example = new UserExample();
        example.or().andIdIn(userIds);
        return userExtendMapper.selectByExample(example);
    }

    /**
     * 判断用户是否在职
     *
     * @param userId
     */
    @Override
    public Boolean isOnJob(Long userId) {
        User user = get(userId);
        if(user.getStatus()==0 && !(user.getDeleted())){
            return true;
        }
        return false;
    }
}
